import pymysql


class FoodConfig:
    def __init__(self, host="localhost", user="root", password="123456", database="food_nutrition_system"):
        """
        初始化FoodConfig类，建立与数据库的连接

        :param host: 数据库主机地址
        :param user: 数据库用户名
        :param password: 数据库密码
        :param database: 数据库名称
        """
        self.host = host
        self.user = user
        self.password = password
        self.database = database
        self.connection = None
        self.cursor = None
        self.connect()

    def connect(self):
        """
        建立与数据库的连接并创建游标
        """
        try:
            self.connection = pymysql.connect(
                host=self.host,
                user=self.user,
                password=self.password,
                database=self.database
            )
            self.cursor = self.connection.cursor()
        except pymysql.Error as e:
            print(f"连接数据库失败: {e}")

    def close_connection(self):
        """
        关闭数据库连接和游标
        """
        if self.cursor:
            self.cursor.close()
        if self.connection:
            self.connection.close()

    def get_food_config(self, food_name:str):
        """
        根据食物名称获取食物的配置信息
        :param food_name: 食物名称
        :return: 食物的配置信息字典，如果未找到则返回None
        """
        query = "SELECT kcal,fat_gram,protein_gram,carbohydrate_gram FROM kcal_information WHERE food_name = %s"
        try:
            self.cursor.execute(query, (food_name,))
            result = self.cursor.fetchone()
            if result:
                return {
                    "热量": result[0],
                    "脂肪": result[1],
                    "蛋白质": result[2],
                    "碳水化合物": result[3]
                }
            return None
        except pymysql.Error as e:
            print(f"获取食物配置信息失败: {e}")

    def update_food_config(self, food_name, new_config):
        """
        根据食物名称更新食物的配置信息

        :param food_name: 食物名称
        :param new_config: 新的配置信息字典，包含calorie、fat、protein、carbohydrate等键值对
        """
        query = ("UPDATE kcal_information SET kcal = %s, fat_gram = %s, protein_gram = %s, carbohydrate_gram = %s "
                 "WHERE food_name = %s")
        try:
            values = (
                new_config["calorie"],
                new_config["fat"],
                new_config["protein"],
                new_config["carbohydrate"],
                food_name
            )
            self.cursor.execute(query, values)
            self.connection.commit()
        except pymysql.Error as e:
            print(f"更新食物配置信息失败: {e}")

    def insert_food_config(self, food_name: str, config: dict):
        """
        向数据库中插入新的食物配置信息

        :param food_name: 食物名称
        :param config: 配置信息字典，包含calorie、fat、protein、carbohydrate等键值对
        """
        query = "INSERT INTO kcal_information (food_name,kcal,fat_gram,protein_gram,carbohydrate_gram) VALUES (%s, %s, %s, %s, %s)"
        try:
            values = (
                food_name,
                config["calorie"],
                config["fat"],
                config["protein"],
                config["carbohydrate"]
            )
            self.cursor.execute(query, values)
            self.connection.commit()
        except pymysql.Error as e:
            print(f"插入食物配置信息失败: {e}")
            return False

    def delete_food_config(self, food_name):
        """
        根据食物名称删除食物的配置信息

        :param food_name: 食物名称
        :return: True if successful, False otherwise
        """
        query = "DELETE FROM kcal_information WHERE food_name = %s"
        try:
            self.cursor.execute(query, (food_name,))
            self.connection.commit()
            return True
        except pymysql.Error as e:
            print(f"删除食物配置信息失败: {e}")
            return False